package com.hugong.yxx.wksp.modules.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.hugong.yxx.wksp.common.bean.AccessToken;
import com.hugong.yxx.wksp.common.bean.UserBean;
import com.hugong.yxx.wksp.common.utils.HttpUtil;
import com.hugong.yxx.wksp.common.bean.Response;
import com.hugong.yxx.wksp.modules.service.OAuthApiService;
import com.qq.connect.utils.RandomStatusGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信第三方登录
 * 第一步：授权，获取code
 * 第二步：通过code,获取accessToken，openid
 * 第三步:通过accessToken、openid获取用户信息
 * @author GunnyZeng
 *
 */
@Component
public class WeiXinOAuthApi implements OAuthApiService {

	@Value("${weixin_appid}")
	private String appid;
	@Value("${weixin_secret}")
	private String secret;
	@Value("${weixin_redirect_URI}")
	private String redirect_URI;
	@Value("${weixin_userinfpApiUrl}")
	private String getUserInfoURL;
	@Value("${weixin_authorizeURL}")
	private String authorizeURL;
	@Value("${weixin_access_token_URL}")
	private String accessTokenURL;
	@Value("${weixin_scope}")
	private String scope;

	@Override
	public String authorize() {
		String state = RandomStatusGenerator.getUniqueState();
        if(scope != null && !scope.equals(""))
        	 return (new StringBuilder())
					 .append(authorizeURL)
					 .append("?appid=").append(appid)
					 .append("&redirect_uri=").append(redirect_URI)
					 .append("&response_type=").append("code")
					 .append("&state=").append(state)
					 .append("&scope=").append(scope)
					 .append("#wechat_redirect").toString();
        else
            return (new StringBuilder())
					.append(authorizeURL)
					.append("?appid=").append(appid)
					.append("&redirect_uri=").append(redirect_URI)
					.append("&response_type=").append("code")
					.append("&state=").append(state)
					.append("#wechat_redirect").toString();
    
	}

	@Override
	public UserBean getUser(Object parame) throws Exception {
		 String code = (String) parame;
		 AccessToken accessToken = getAccessToken(code);
         UserBean user =  new UserBean();
         if (accessToken.getAccess_token().equals("")) {
             throw new Exception("授权失败！");
         } else {
             String openID = accessToken.getOpenid();
             //获取用户信息
             Response response = showUser(accessToken);
             user = JSON.parseObject(response.getBody(),UserBean.class);
             
             if (ObjectUtil.isNotNull(user)) {
				 return user;
             } else {
            	 throw new Exception("很抱歉，我们没能正确获取到您的信息! ");
             }
         }
	}
	
	/**
	 * 获取AccessToken
	 * @param code
	 * @return
	 * @throws Exception 
	 */
	private AccessToken getAccessToken(String code) throws Exception{
		Map<String, String> params = new HashMap<>();
		params.put("appid", appid);
		params.put("secret", secret);
		params.put("grant_type", "authorization_code");
		params.put("code", code);
		return new AccessToken(HttpUtil.post(
				accessTokenURL, params));
	}
	/**
	 * 授权后获取用户json数据
	 * @param accessToken
	 * @return
	 * @throws Exception 
	 */
	 private Response showUser(AccessToken accessToken) throws Exception {
		 Map<String, String> params = new HashMap<>();
		 params.put("openid", accessToken.getOpenid());
		 params.put("access_token", accessToken.getAccess_token());
		 params.put("lang", "zh_CN");
		 Response response=HttpUtil.get(getUserInfoURL,params);
		 return  response;
	 }


}
